package com.example.portdemo.date.repository;

import com.example.portdemo.date.dao.NewsDao;
import com.example.portdemo.date.model.NewsEntity;
import com.example.portdemo.service.NewsApiService;
import com.example.portdemo.service.NewsRepository;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewsRepositoryImpl implements NewsRepository {

    private URI apiService;
    private NewsDao newsDao;

    public NewsRepositoryImpl(URI apiService, NewsDao newsDao) {
        this.apiService = apiService;
        this.newsDao = newsDao;
    }

    @Override
    public void getNewsList(Callback<List<NewsEntity>> callback) {
        List<NewsEntity> cachedNews = newsDao.getNewsList();
        if (cachedNews.isEmpty()) {
            apiService.getNewsList().enqueue(new Callback<List<NewsEntity>>() {
                @Override
                public void onResponse(Call<List<NewsEntity>> call, Response<List<NewsEntity>> response) {
                    if (response.isSuccessful()) {
                        List<NewsEntity> newsList = response.body();
                        newsDao.insertAll(Arrays.asList(newsList.toArray(new NewsEntity[0])));
                        callback.onResponse(newsList);
                    } else {
                        callback.onFailure(call, new IOException("Error: " + response.code()));
                    }
                }

                @Override
                public void onFailure(Call<List<NewsEntity>> call, Throwable t) {
                    callback.onFailure(call, t);
                }
            });
        } else {
            callback.onResponse(cachedNews);
        }
    }
}